package org.sam.beatles.config;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * 内存数据源配置
 * 
 * @author sam
 *
 */
@Configuration
@EnableJpaRepositories(basePackages = "org.sam.beatles.dao", entityManagerFactoryRef = "memoryManagerFactory", transactionManagerRef = "memoryTransactionManager")
public class MemoryDataSourceConfigure {

	/**
	 * 注入数据源
	 */
	@Autowired
	@Qualifier("memoryDataSource")
	private DataSource dataSource;

	@Autowired
	private JpaProperties jr;

	/**
	 * {@inheritDoc}
	 * 
	 * @param builder
	 * @return
	 */
	@Bean
	public LocalContainerEntityManagerFactoryBean memoryManagerFactory(EntityManagerFactoryBuilder builder) {
		Map<String, String> properties = new HashMap<String, String>(jr.getProperties());
		properties.put("hibernate.hbm2ddl.auto", "update");
		return builder.dataSource(dataSource).properties(properties).packages("org.sam.beatles.pojo")
				.persistenceUnit("memory").build();
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @param builder
	 * @return
	 */
	@Bean
	public PlatformTransactionManager memoryTransactionManager(EntityManagerFactoryBuilder builder) {
		LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = memoryManagerFactory(builder);
		return new JpaTransactionManager(localContainerEntityManagerFactoryBean.getObject());
	}
}
